﻿using System;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Net;

namespace VIID.Client
{
    //public partial class Client
    //{public partial class Client
    public partial class Client
    {
        /// <summary>
        /// 注册
        /// </summary>
        /// <returns></returns>
        public bool Register()
        {
            //初始化
            if (string.IsNullOrEmpty(_options.baseServer))
            {
                Console.WriteLine("服务器地址错误");
                return false;
            }

            if (_options.deviceID.Length != 20 && _options.videoID.Length != 20)
            {
                Console.WriteLine("设备、视频编码错误");
                return false;
            }
            if (string.IsNullOrEmpty(_options.userName) || string.IsNullOrEmpty(_options.password))
            {
                Console.WriteLine("用户名或密码为空");
                return false;
            }

            //初始化
            /*
            _httpClient = new HttpClient()
            {
                BaseAddress = new Uri(_options.baseServer),
                Timeout = new TimeSpan(0, 0, 10)
            };
            if (_options.baseServer.StartsWith("https"))
                global::System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
            _httpClient.DefaultRequestHeaders.Accept.Add(
              new MediaTypeWithQualityHeaderValue("application/VIID+JSON"));
            _httpClient.DefaultRequestHeaders.Add("User-Identify", _options.deviceID);
            _httpClient.DefaultRequestHeaders.Add("User-Agent", "GAT1400 Client 1.0");
            */
            _timer = new global::System.Timers.Timer()
            {
                Interval = _options.keepLiveInterval
            };

            var _request = new RegisterRoot()
            {
                RegisterObject = new Register()
                {
                    DeviceID = _options.deviceID
                }
            };

            //注册登录
            //string postData = JsonSerializer.Serialize(r,typeof(RegisterRequestObject), GAT1400.jsonSetting);
            string postData = _request.ToJSON();

            HttpContent _httpContent = Utils.content(postData);
            HttpResponseMessage response = _httpClient.PostAsync("/VIID/System/Register", _httpContent).Result;

            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
#if DEBUG
                Console.WriteLine("二次认证");
#endif
                var authName = "";

                foreach (var header in response.Headers)
                {
                    if ("WWW-Authenticate" == header.Key)
                        authName = header.Value.ToArray()[0];
                }
                if (string.IsNullOrEmpty(authName))
                    return false;

                var authValue = Utils.RFC2617.encode(authName, _options.userName, _options.password, "POST", "/VIID/System/Register");

                //_httpClient.DefaultRequestHeaders.Add("Authorization", authValue);
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Digest", authValue);//new AuthenticationHeaderValue("Basic", authValue);
                Console.WriteLine("{0}--{1}",
                authName,authValue);
                //第二次POST
                response = _httpClient.PostAsync("/VIID/System/Register", _httpContent).Result;
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    var content = Utils.Stream.read(response.Content.ReadAsStream());
                    var result = content.ToObject<ResponseStatusRoot>();
                    _httpClient.DefaultRequestHeaders.Authorization = null;
                    if ((int)responseStatus.STATUS_OK != result.ResponseStatusObject.StatusCode)
                    {
                        _httpClient.DefaultRequestHeaders.Authorization = null;
#if DEBUG
                        Console.WriteLine("登录失败:{0}", result.ResponseStatusObject.StatusString);
#endif
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            onChangeState(true);



            return true;
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public bool UnRegister()
        {
            if (!_options.State)
                return true;

            string postData = (new UnRegisterRoot() { UnRegisterObject = new UnRegister() { DeviceID = _options.deviceID } }).ToJSON();

            HttpContent _httpContent = Utils.content(postData);

            HttpResponseMessage response = _httpClient.PostAsync("/VIID/System/UnRegister", _httpContent).Result;
            if (response.StatusCode == HttpStatusCode.Unauthorized)
            {
                var authName = "";

                foreach (var header in response.Headers)
                {
                    if ("WWW-Authenticate" == header.Key)
                        authName = header.Value.ToArray()[0];
                }

                var authValue = Utils.RFC2617.encode(authName, _options.userName, _options.password, "POST", "/VIID/System/UnRegister");
                //httpContent.Headers.Add("Authorization", authValue);
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Digest", authValue);

                //第二次POST
                response = _httpClient.PostAsync("/VIID/System/UnRegister", _httpContent).Result;
                if (response.StatusCode == HttpStatusCode.Unauthorized)
                {
                    var content = Utils.Stream.read(response.Content.ReadAsStream());
                    var result = content.ToObject<ResponseStatusRoot>();

                    if ((int)responseStatus.STATUS_OK != result.ResponseStatusObject.StatusCode)
                    {
                        _httpClient.DefaultRequestHeaders.Authorization = null;
                        Console.WriteLine("注销失败:{0}", result.ResponseStatusObject.StatusString);
                        return false;
                    }
                }

            }
            onChangeState(false);
            return true;
        }
        /// <summary>
        /// 校时
        /// </summary>
        public void SynTime()
        {
            if (!_options.State)
                return;

            var response = _httpClient.GetAsync("/VIID/System/Time").Result;

            if (HttpStatusCode.OK == response.StatusCode)
            {
                var content = Utils.Stream.read(response.Content.ReadAsStream());
                var result = content.ToObject<SystemTimeRoot>();


                DateTime dt = result.SystemTimeObject.LocalTime;
                TimeSpan ts = DateTime.Now.Subtract(dt);
                _timeSpan = ts.TotalSeconds;
                Console.WriteLine("服务器时间:{0},与本地时间差{1}.", dt.ToString("yyyy-MM-dd HH:mm:ss"), _timeSpan);
            }
            else
            {
                Console.WriteLine("校时失败:{0}", response.Content);
            }
        }
        /// <summary>
        /// 保活
        /// </summary>
        /// <returns></returns>
        public bool keepAlive()
        {
            if (!_options.State)//状态在线
                return false;

            string postData = (new KeepaliveRoot() { KeepaliveObject = new Keepalive() { DeviceID = _options.deviceID } }).ToJSON();

            HttpContent _httpContent = Utils.content(postData);


            HttpResponseMessage response = _httpClient.PostAsync("/VIID/System/Keepalive", _httpContent).Result;
            if (response.StatusCode == HttpStatusCode.OK)
            {
                var content = Utils.Stream.read(response.Content.ReadAsStream());
                var result = content.ToObject<ResponseStatus>();

                if ((int)responseStatus.STATUS_OK != result.StatusCode)
                {
                    Console.WriteLine("保活接口失败:{0}", result.StatusString);
                    onChangeState(false);
                    //_status = false;
                    return false;
                }
                return true;
            }
            onChangeState(false);
            //_status = false;
            //_timer.Enabled = false;
            return false;
        }
    }
}
//}